﻿using Adp;
using Microsoft.AspNetCore.Mvc;
using Yqd.Models;
using System.Linq;
using Adp.Common;
using System;
using Yqd.Core;
using Yqd.Controllers.Filter;
using Yqd.Enm;
using System.Collections.Generic;
using Newtonsoft.Json;

namespace Yqd.Controllers
{
    [Area("Yqd")]
    public class WxCoordinateController : Controller
    {
        YqdContext ctx;

        public WxCoordinateController(YqdContext ctx)
        {
            this.ctx = ctx;
        }

       [User]
        public ActionResult GetList()
        {
            var page = Form.GetInt("page", 1);
            var pagesize = Form.GetInt("pagesize", 2);
            var l = WxUser.LogonInfo;

            var source = Form.GetString("source");
            //Logs.Information<UserHostService>($"WxCoordinate/GetList用户登录信息 :{JsonConvert.SerializeObject(l)}，来源:{source}");

            var sql = "isdel=0 and [UnitCode]={0}";
            var (totalcount, data) = ctx.Database.SqlPager<Yqd_Coordinate>((page - 1) * pagesize, pagesize, "*", sql, "[Instime] desc", l.UnitCode);
            var cIDs = data.Select(it => it.CoordinateID).ToArray();
            var assign = ctx.Yqd_Assign.Where(it => cIDs.Contains(it.ItemID) && it.ItemType == 事项类型.协同管理).Select(it => new { it.ItemID, it.ItemType, it.CompleteLimit}).ToList();
            var tIDs = data.Select(it => it.TaskID).ToArray();
            var tasks = ctx.Yqd_Task.Where(it => tIDs.Contains(it.TaskID)).Select(it => new { it.TaskID, it.TaskName, it.LeaderUnitName, it.CreateTime, it.FAreaCode, it.TaskStatus }).ToList();
            dynamic t = null;
            return this.ToJson(new
            {
                success = true,
                totalcount,
                data = data.Select(it => new
                {
                    it.CoordinateID,
                    TaskID = it.TaskID.ToString(),
                    (t = tasks.FirstOrDefault(n => n.TaskID == it.TaskID))?.TaskName,
                    t.LeaderUnitName,
                    TaskStatus = Enum.GetName(typeof(任务状态), t.TaskStatus),
                    CreateTime = t.CreateTime.ToString("yyyy-MM-dd"),
                    Content = it.Item,
                    Status = Enum.GetName(typeof(任务状态), it.Status),
                    AssignLimit = assign.FirstOrDefault(n => n.ItemID == it.CoordinateID && n.ItemType == 事项类型.协同管理)?.CompleteLimit.ToString("yyyy-MM-dd")
                })
            });
        }

        /// <summary>
        /// 添加协同事项
        /// </summary>
        /// <returns></returns>
       [User]
        public IActionResult Add(Yqd_Coordinate model)
        {
            if (!ModelState.IsValid)
            {
                return this.ToJson(new
                {
                    success = false,
                    stateMsg = from sk in ModelState.AsEnumerable()
                               where sk.Value.Errors.Count() > 0
                               select new { id = sk.Key, msg = sk.Value.Errors.FirstOrDefault().ErrorMessage }
                });
            }
            model.Status = 任务状态.正常推进;
            model.Instime = DateTime.Now;
            model.EmployeeCode = WxUser.LogonInfo.EmployeeCode;
            model.UnitCode = WxUser.LogonInfo.UnitCode;
            ctx.Yqd_Coordinate.Add(model);
            var ret = ctx.SaveChanges();
            if (ret > 0)
            {
               TaskLogService.AddLog(model.TaskID, "向" + ctx.Yqd_User.FirstOrDefault(it => it.EmployeeCode == model.Coordinator)?.Name + "发起了协调");
            }
            return this.ToJson(new
            {
                success = true,
                ret
            });
        }

        [User]
        public ActionResult GetCoordinator()
        {
            var l = WxUser.LogonInfo;
            var data = new List<dynamic>();
            if (l != null && !string.IsNullOrWhiteSpace(l.OrganizationCode))
            {
                var u = ctx.Yqd_User.Where(it =>it.UnitCode == l.OrganizationCode && ("," + it.Roles + ",").Contains("," + (int)角色类型.部门领导 + ","));
                data.AddRange(u.Select(it => new
                {
                    it.Name,
                    Value = it.EmployeeCode
                }));
            }
            var r = ctx.Yqd_User.Where(it => ("," + it.Roles + ",").Contains("," + (int)角色类型.协调人 + ","));
            data.AddRange(r.Select(it => new
            {
                it.Name,
                Value = it.EmployeeCode
            }));
            return this.ToJson(new
            {
                success = true,
                data
            });
        }

        [User]
        public ActionResult Delete()
        {
            var l = WxUser.LogonInfo;
            if (!l.Role.Contains(角色类型.管理员))
            {
                return this.ToJson(new
                {
                    success = false,
                    msg = "无权限删除"
                });
            }
            var CoordinateID = Form.GetInt("CoordinateID");
            var ret = ctx.Database.ExecuteSql("update Yqd_Coordinate set IsDel=1 where CoordinateID={0};", CoordinateID);
            //if (ret > 0)
            //{
            //    var m = ctx.Yqd_Supervise.FirstOrDefault(it => it.SuperviseID == SuperviseID);
            //    TaskLogService.AddLog(m.TaskID, "删除了督导意见(" + m.Content + ")");
            //}
            return this.ToJson(new
            {
                success = true,
                ret
            });

            //var ret = ctx.Database.ExecuteSql("delete from Yqd_Coordinate where CoordinateID={0}", CoordinateID);
            //return this.ToJson(new
            //{
            //    success = true,
            //    ret
            //});
        }
    }
}
